package controller

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Method"
	"gitee.com/fierce_wolf/go-fox-edge-common/httpserver"
	"go-fox-edge-kernel-manager/repository"
	"net/http"
)

type repoCloudIotTemplateController struct {
}

func (e *repoCloudIotTemplateController) init() {
	httpserver.Server.POSTRaw("/repository/iot-template/page", e.selectPageList)
	httpserver.Server.POSTRaw("/repository/iot-template/version/object/entities", e.selectOperateList)
	httpserver.Server.POSTRaw("/repository/iot-template/version/install", e.installVersionEntity)
	httpserver.Server.POSTRaw("/repository/iot-template/version/page", e.selectVersionPageList)
	httpserver.Server.POSTRaw("/repository/iot-template/version/object/entity", e.getVersionPageList)
}

func (e *repoCloudIotTemplateController) selectPageList(context httpserver.Context, body map[string]interface{}) (interface{}, error) {
	result, err := repository.CloudRemoteService.QueryCloudCompIotTemplatePage(body)
	if err != nil {
		return nil, err
	}

	data := Map.GetMap(result, "data", make(map[string]interface{}))
	list := Map.GetSlice(data, "list", make([]interface{}, 0))

	// 扩展安装状态信息
	repository.CloudIotTemplateInstallStatus.Extend(list)

	return result, nil
}

func (e *repoCloudIotTemplateController) selectOperateList(context httpserver.Context, body map[string]interface{}) (interface{}, error) {
	return repository.CloudRemoteService.QueryCloudIotTemplateObjectList(body)
}

func (e *repoCloudIotTemplateController) installVersionEntity(context httpserver.Context, body map[string]interface{}) (interface{}, error) {
	// 查询数据
	result, err := repository.CloudRemoteService.QueryCloudIotTemplateVersionList(body)
	if err != nil {
		return result, nil
	}

	// 检查状态
	if http.StatusOK != Map.GetInt(result, "code", 0) {
		return result, nil
	}

	// 提取数据
	list := Map.GetSlice(result, "data", make([]interface{}, 0))
	if Method.HasEmpty(list) {
		return result, nil
	}

	data := list[0]

	// 扩展安装状态信息
	repository.LocalCompService.InstallVersion("iot-template", data.(map[string]interface{}))

	return result, nil
}

func (e *repoCloudIotTemplateController) selectVersionPageList(context httpserver.Context, body map[string]interface{}) (interface{}, error) {
	return repository.CloudRemoteService.QueryCloudIotTemplateVersionPage(body)
}

func (e *repoCloudIotTemplateController) getVersionPageList(context httpserver.Context, body map[string]interface{}) (interface{}, error) {
	return repository.CloudRemoteService.QueryCloudIotTemplateObjectEntity(body)
}
